package top.blackr.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Builder;
import lombok.Data;
import net.dreamlu.mica.http.HttpRequest;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 消息模板发送
 *
 * @author BlackR
 */
public class MsgUtils {

    private static final String APP_ID = "wxed***********bcdf";
    private static final String APP_SECRET = "935e77********************59ac";

    private static final String URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";
    private static final String TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    /**
     * 发送微信推送消息
     *
     * @param msgTemplateId 消息模板id
     * @param openId 微信openId
     * @param <T> 模板参数
     */
    public static <T extends DataSource> void sendWeChatMsg(String msgTemplateId, String openId, T dataSource) {
        Map<String, Object> dataMaps = BeanUtil.beanToMap(dataSource, false, true);
        //整体参数map
        Map<String, Object> paramMap = new HashMap<>(7);

        // 点击消息跳转小程序
        // Map<String, String> miniprogramMap = new HashMap<>();
        // 模板跳转小程序AppId
        // miniprogramMap.put("appid", APP_ID);
        // 模板跳转小程序路径
        // miniprogramMap.put("pagepath", miniProgramPagePath);
        // paramMap.put("miniprogram", miniprogramMap);

        dataMaps.forEach((key, value) -> {
            // 有时间再扩展集合对象
            if (value instanceof String || value instanceof Long || value instanceof Integer) {
                // 直接覆盖原value
                dataMaps.put(key, DataEntity.builder().color(getColor()).value(String.valueOf(value)).build());
            }
        });

        paramMap.put("touser", openId);
        paramMap.put("template_id", msgTemplateId);
        // 网页跳转地址
        paramMap.put("url", "");
        paramMap.put("data", dataMaps);
        String postResult = HttpRequest.post(String.format(URL, getToken()))
                .bodyJson(paramMap)
                .execute()
                .asString();
        System.out.printf("openId : %s ,推送结果：%s", openId, postResult);
    }

    /**
     * 获取token
     *
     * @return token
     */
    public static String getToken() {
        String tokenJsonStr = HttpRequest.get(String.format(TOKEN, APP_ID, APP_SECRET)).execute().asString();
        JSONObject readMap = JSONUtil.parseObj(tokenJsonStr);
        String token = readMap.getStr("access_token");
        System.out.printf("获取到的TOKEN :%s\n", token);
        return token;
    }

    @Data
    @Builder
    static class DataEntity implements Serializable {
        private String value;
        private String color;
    }

    /**
     * 随机生成颜色代码
     *
     * @return 十六进制颜色
     */
    private static String getColor() {
        //生成随机对象
        Random random = new Random();
        //生成红色颜色代码
        String red = Integer.toHexString(random.nextInt(256)).toUpperCase();
        //生成绿色颜色代码
        String green = Integer.toHexString(random.nextInt(256)).toUpperCase();
        //生成蓝色颜色代码
        String blue = Integer.toHexString(random.nextInt(256)).toUpperCase();

        //判断红色代码的位数
        red = red.length() == 1 ? "0" + red : red;
        //判断绿色代码的位数
        green = green.length() == 1 ? "0" + green : green;
        //判断蓝色代码的位数
        blue = blue.length() == 1 ? "0" + blue : blue;
        //生成十六进制颜色值
        return "#" + red + green + blue;
    }
}
